<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\User as LibraryUser;
use fast\Random;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'mobile,unique_id,invite.mobile,invite.unique_id';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;

        $marketingLevelList = [];
        $marketingLevelList["1"] = "一星董事";
        $marketingLevelList["2"] = "二星董事";
        $marketingLevelList["3"] = "三星董事";
        $this->assignconfig('marketingLevelList', $marketingLevelList);

        $expertLevelList = [];

        $expertLevelList["0"] = "----";
        $expertLevelList["1"] = "一星达人";
        $expertLevelList["2"] = "二星达人";
        $expertLevelList["3"] = "三星达人";
        $this->assignconfig('expertLevelList', $expertLevelList);

        $yesorNolList = [];
        $yesorNolList["0"] = "否";
        $yesorNolList["1"] = "是";
        $this->assignconfig('yesorNolList', $yesorNolList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list_info = db("user as user")
                ->join('user invite', "invite.id=user.parent_user_id", "LEFT")
                ->field("user.*,invite.unique_id as parent_user_unique_id,invite.username as parent_user_username,invite.mobile as parent_user_mobile")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // exit(db()->getLastSql());
            // exit(print_r($list_info));
            $list = $list_info->items();
            $total = $list_info->total();
            foreach ($list as $k => $v) {
                // exit(print_r($v));
                $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);

                $list[$k]["parent_user_unique_id"] = $v["parent_user_unique_id"] ? $v["parent_user_unique_id"] : "";
                $list[$k]["parent_user_username"] = $v["parent_user_username"] ? $v["parent_user_username"] : "";
                $list[$k]["parent_user_mobile"] = $v["parent_user_mobile"] ? $v["parent_user_mobile"] : "";

                unset($list[$k]["password"]);
                unset($list[$k]["salt"]);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    // public function index()
    // {
    //     $this->relationSearch = true;
    //     $this->searchFields = "invite.mobile";//增加三个别表的查询功能,若未进行设置，默认只能快速查询id的值
    //     //设置过滤方法
    //     $this->request->filter(['strip_tags', 'trim']);
    //     if (false === $this->request->isAjax()) {
    //         return $this->view->fetch();
    //     }

    //     //如果发送的来源是 Selectpage，则转发到 Selectpage
    //     if ($this->request->request('keyField')) {
    //         return $this->selectpage();
    //     }
    //     [$where, $sort, $order, $offset, $limit] = $this->buildparams();
    //     $list = $this->model
    //         ->with('invite')
    //         ->where($where)
    //         ->order($sort, $order)
    //         ->paginate($limit);
    //     $item = $list->items();
    //     foreach ($item as $k => $v) {
    //         // exit(print_r($v));
    //         $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);
    //         unset($list[$k]["password"]);
    //         unset($list[$k]["salt"]);
    //     }
    //     $result = ['total' => $list->total(), 'rows' => $item];
    //     return json($result);
    // }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();

            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {

                //检测手机号码是否已存在
                $mobile = $params["mobile"] ?? "";
                if ($mobile) {
                    $old_user = db("user")->where("mobile", $mobile)->find();
                    if ($old_user) {
                        $this->error("手机号已经存在");
                    }
                }

                if ($params["password"]) {
                    $params["salt"] = Random::alnum();
                    $params["password"] = Auth::instance()->getEncryptPassword($params["password"], $params["salt"]);
                } else {
                    unset($params["password"]);
                }

                //获取推荐人
                if ($params["parent_user_unique_id"]) {
                    $parent_user = db("user")->where("unique_id", $params["parent_user_unique_id"])->find();
                    if ($parent_user) {
                        $params["parent_user_id"] = $parent_user["id"];
                        if ($parent_user["expert_level"] == 0) {
                            $this->error("推荐人的级别必须是达人级别以上");
                        }
                    } else {
                        $this->error("不存在此分享码");
                    }
                } else {
                    $this->error("必须填写推荐人");
                }
                unset($params["parent_user_unique_id"]);

                //必须是达人级别以上
                 if (intval($params["expert_level"]) <= 0) {
                     $this->error("后台添加的用户必须是达人级别以上");
                 }

                //省市区
                $params["province"] = "";
                $params["city"] = "";
                $params["area"] = "";
                if (isset($params["province_id"]) && $params["province_id"]) {
                    $province = db("area_code")->where("id", $params["province_id"])->value("name");
                    $params["province"] = $province;
                }
                if (isset($params["city_id"]) && $params["city_id"]) {
                    $city = db("area_code")->where("id", $params["city_id"])->value("name");
                    $params["city"] = $city;
                }
                if (isset($params["area_id"]) && $params["area_id"]) {
                    $area = db("area_code")->where("id", $params["area_id"])->value("name");
                    $params["area"] = $area;

                    $other_user = db("user")->where("area_id", $params["area_id"])->find();
                    if ($other_user) {
                        $this->error("此区域已经存在一个区域经理商");
                    }
                }


                // exit(print_r($params));
                $result = $this->model->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }

                $admin = $this->auth->getUserInfo();

                $uqi = 0;
                do{
                    if($uqi>5){
                       $NewUniqueId = rand(10000000, 39999999);
                    }else{
                       $NewUniqueId = rand(40000000, 99999999);
                    }
                    $countUnique = db("user")->field('id')->where(['unique_id'=>$NewUniqueId])->count();
                    if($uqi>10){
                        throw new Exception("生成邀请码失败");
                    }
                    $uqi++;
                }while ($countUnique);
                db("user")->where("id", $this->model->id)->update(["unique_id" => $NewUniqueId]);

                //没有直推人的情况，自己作为树形顶级，占位和关系链直接插入
                if ($params["parent_user_id"] == 0) {
                    //自己作为树形顶级,插入自己的点位和级别关系，不需要再走定时任务的升级流程
                    LibraryUser::insertTopPositionAndRelation($this->model->id, $params["expert_level"], $admin["id"]);
                } else {
                    //有推荐人的情况，让定时任务去处理这个用户的级别关系和点位。
                    if (intval($params["expert_level"]) > 0) {


                    }
                }
                $this->success();
            }
            $this->error();
        }

        $expertLevelList = [];
        $expertLevelList["0"] = "其他";
        $expertLevelList["1"] = "团长";
        $expertLevelList["2"] = "家庭酒庄";
        $expertLevelList["3"] = "区县代理商";
        $this->view->assign('expertLevelList', build_select('row[expert_level]', $expertLevelList, "0", ['class' => 'form-control selectpicker', 'id'=>'id_expert_level']));

        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), "", ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $hiddenInfo = \think\Db::name('expert_relation')->where(['user_id'=>$row->id])->find();
        if(!empty($hiddenInfo)){
            $row->is_hidden = $hiddenInfo['status']==1?0:1;
        }else{
            $row->is_hidden = 0;
        }
        if ($this->request->isPost()) {
            $this->token();

            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                
                if(empty($hiddenInfo) && $params['is_hidden']==1){
                    $this->error('不是达人！不能隐藏！');
                }
                unset($row->is_hidden);
                //检测手机号码是否已存在
                $mobile = $params["mobile"] ?? "";
                if ($mobile) {
                    $old_user = db("user")->where("mobile", $mobile)->find();
                    if ($old_user  && $row->mobile != $mobile) {
                        $this->error("手机号已经存在");
                    }
                }

                if ($params["password"]) {
                    $params["salt"] = Random::alnum();
                    $params["password"] = Auth::instance()->getEncryptPassword($params["password"], $params["salt"]);
                } else {
                    unset($params["password"]);
                }

                //省市区
                $params["province"] = "";
                $params["city"] = "";
                $params["area"] = "";
                if (isset($params["province_id"]) && $params["province_id"]) {
                    $province = db("area_code")->where("id", $params["province_id"])->value("name");
                    $params["province"] = $province;
                }
                if (isset($params["city_id"]) && $params["city_id"]) {
                    $city = db("area_code")->where("id", $params["city_id"])->value("name");
                    $params["city"] = $city;
                }
                if (isset($params["area_id"]) && $params["area_id"]) {
                    $area = db("area_code")->where("id", $params["area_id"])->value("name");
                    $params["area"] = $area;

                    $other_user = db("user")->whereNotIn("id", [$row->id])->where("area_id", $params["area_id"])->find();
                    if ($other_user) {
                        $this->error("此区域已经存在一个区域经理商");
                    }
                }

                $old_expert_level = $row->expert_level;

                
                if($params['is_hidden']==1){
                     \think\Db::name('expert_relation')->where(['user_id'=>$row->id])->data(["status"=>0])->update();
                }else{
                    \think\Db::name('expert_relation')->where(['user_id'=>$row->id])->data(["status"=>1])->update();
                }
                unset($params['is_hidden']);
                
                

                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                $admin = $this->auth->getUserInfo();

                //如果变更了达人级别 或改了市场级别
                if ($old_expert_level != $params["expert_level"]) {

                    LibraryUser::changeLevel($row->id, $params["expert_level"]);

                    //插入升级记录
                    $history = [
                        "is_system" => 1,
                        "admin_id" =>  $admin["id"],
                        "user_id" => $row->id,
                        "before_level" => $old_expert_level,
                        "after_level" => $params["expert_level"],
                        "note" => "后台设置升级",
                        "addtime" => time()
                    ];
                    db("expert_upgrade_history")->insert($history);
                }
                $this->success();
            }
            $this->error();
        }

        //获取推荐人
        if ($row->parent_user_id) {
            $parent_user = db("user")->where("id", $row->parent_user_id)->find();
            if ($parent_user) {
                $row->parent_user_unique_id = $parent_user["unique_id"];
                // exit(print_r($parent_user));
            }
        }
        $row->parent_user_unique_id = $row->parent_user_unique_id ?? "";


        $this->view->assign("row", $row);


//        $marketingLevelList = [];
//        $marketingLevelList["0"] = "----";
//        $marketingLevelList["1"] = "一星董事";
//        $marketingLevelList["2"] = "二星董事";
//        $marketingLevelList["3"] = "三星董事";
//
//        $this->view->assign('marketingLevelList', build_select('row[marketing_level]', $marketingLevelList, $row['marketing_level'], ['class' => 'form-control selectpicker']));

        $expertLevelList = [];
        $expertLevelList["0"] = "其他";
        $expertLevelList["1"] = "团长";
        $expertLevelList["2"] = "家庭酒庄";
        $expertLevelList["3"] = "区县代理商";
        $this->view->assign('expertLevelList', build_select('row[expert_level]', $expertLevelList, $row['expert_level'], ['class' => 'form-control selectpicker', 'id'=>'id_expert_level']));

        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
}
